import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { validateTypes } from '@/utils/validate'

let isShowingReLoginWin = false
function showReLoginWin() {
  if (isShowingReLoginWin) return
  isShowingReLoginWin = true
  MessageBox.alert('可点击确定按钮刷新页面', '登录失效', {
    type: 'warning'
  }).then(() => {
    store.dispatch('user/getRedirectUrl')
  }).finally(() => {
    isShowingReLoginWin = false
  })
}

const responseHandler = Vue => ({
  responseResolve(response) {
    const { isResponseHandle = true } = response.config
    const data = response.data || {}
    if (!isResponseHandle || validateTypes(data, 'Blob')) {
      return data
    }
    const errCode = data.errCode
    const success = data.success
    if (!success) {
      Message.error({
        title: '错误',
        message: data.errMessage
      })
    }
    if (!errCode) return data
    throw data.errMessage
  },
  async responseReject(error) {
    const config = error.config
    if (config && config.handleError) {
      return Promise.reject(error)
    }
    if (!error.response) {
      // 极端情况下
      Message.error({
        title: '错误',
        message: error.message || '请求发生错误, 请稍后再试'
      })
      return Promise.reject(error)
    }
    const data = error.response.data
    if (error.response.status === 404) {
      Message.error({
        message: '请求的接口没有找到！请联系开发查看',
        title: '请求失败'
      })
    } else if (error.response.status === 403) {
      Message.error({
        message: 'Forbidden',
        description: data.message
      })
    } else if (error.response.status === 401) {
      if (process.env.NODE_ENV !== 'development') {
        showReLoginWin()
      }
    }
    return Promise.reject(error)
  }
})
export default responseHandler
